<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
	<meta http-equiv="cache-control" content="public">
	<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> -->
	<!-- <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'"> -->
	<title>腾讯课堂统计</title>
	<script>
		window.nodeRequire = require;
		delete window.require;
		delete window.exports;
		delete window.module;
	</script>
	<script src="https://unpkg.com/vue/dist/vue.js"></script>
	<!-- 引入样式 -->
	<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
	<!-- 引入组件库 -->
	<script src="https://unpkg.com/element-ui/lib/index.js"></script>
	<script src="https://cdn.bootcss.com/xlsx/0.15.6/xlsx.extendscript.js"></script>
	<script src="https://cdn.bootcss.com/xlsx/0.15.6/xlsx.full.min.js"></script>
	<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
	<div id="app">
		<el-input v-model="url" placeholder="请输入腾讯课堂网址"></el-input>
		<br />
		<br />
		<el-tooltip content="如果拥有分页,请点击下一页，然后继续点击记录考勤,考勤结束请按结束考勤按钮" placement="bottom" effect="dark">
			<el-button id="btn" @click="list">记录考勤</el-button>
		</el-tooltip>
		<el-button @click="end">结束考勤</el-button>
		<el-button @click="open">使用说明</el-button>
		<br />
		<br />
		<webview id="web" style="height: 600px;" :src="url" autosize="on" minwidth="576" minheight="432"
			preload="./test.js"></webview>
		<br />
		<el-button @click="addClass">添加班级</el-button>
		<br />
		<br />
		<!-- execel读取 -->
		<input type="file" id="file" style="display:none;"
			accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

		<el-collapse accordion>
			<el-collapse-item v-for="(item,index) in classlist" :key="index" :title='item.title' :name="index">
				<el-button type="button" class="addstudent" :index="index" onclick="selectFile(this)">添加学生</el-button>

				<!-- 导出数据 -->
				<el-button type="button" class="btn green" :index="index" onclick="method5('table',this)">导出考勤表格
				</el-button>
				<br />
				<br />
				<!-- 数据显示 -->
				<el-table :data="item.student" border style="width: 100%" class="table">
					<el-table-column align="center" prop="id" label="学号"></el-table-column>
					<el-table-column align="center" prop="name" label="姓名"></el-table-column>
					<el-table-column label="考勤" align="center">
						<template slot-scope="scope">
							<p v-for="(i,num) in scope.row.state" :key="num">
								<span v-if="i.check == true">第{{num+1}}次考勤：√</span>
								<span v-if="i.check != true">第{{num+1}}次考勤：缺席</span>
							</p>
						</template>
					</el-table-column>
				</el-table>
			</el-collapse-item>
		</el-collapse>
	</div>
</body>

</html>

<script>
	new Vue({
		el: '#app',
		data: {
			url: '', //https://ke.qq.com/webcourse/index.html#cid=1117287&term_id=101213423&taid=6186969110482023&lite=1
			studentList: new Set(),
			classlist: [
				{
					title: '班级1',
					student: []
				}
			],
			absentList: [],
			num: 0
		},
		methods: {
			list() {
				const wb = document.querySelector('#web');
				wb.addEventListener("ipc-message", (event) => {
					var aaa = event.channel;
					var strs = new Array();
					strs = aaa.split(",");
					for (var i = 0; i < strs.length; i++) {
						this.studentList.add(strs[i])
					}
				})
				wb.send('ping')
			},
			addClass() {
				let index = this.classlist.length + 1;
				this.classlist.push({
					title: '班级' + Number(index),
					student: []
				})
			},
			end() {
				this.num++
				for (var i = 0; i < this.classlist.length; i++) {
					for (var j = 0; j < this.classlist[i].student.length; j++) {
						//默认不存在
						var isHere = false;
						for (let index = 0; index < this.studentList.length; index++) {
							if (this.classlist[i].student[j].name == this.studentList[index]) {
								isHere = true
							}
						}
						if (isHere == false) this.absentList.push(this.classlist[i].student[j].name)
						this.classlist[i].student[j].state.push({ check: isHere })
					}
				}
				if (this.absentList.length > 0) {
					this.$notify({
						title: '第' + this.num + '次考勤缺席名单',
						message: this.absentList,
						type: 'warning',
						duration: 0
					});
				} else {
					this.$notify({
						title: '全员到齐',
						message: '所有学生到齐',
						type: 'success'
					});
				}

				this.studentList = new Set();
				this.absentList = [];
			},
			open() {
        this.$alert('<h4>1.在顶部输入需要监听的课程网址</h4><h4>2.往下滑动，找到班级1，如果需要添加多个班级，请点击‘添加班级按钮’</h4><h4>3.点击‘添加学生’按钮，引入execl名单进行批量导入，execl规格如下：(请注意,如果需要导入多个文件，文件不能拥有相同名称，否则导入失败，请重新启动软件)</h4>学号&nbsp;&nbsp;&nbsp;&nbsp;姓名<br/>1001&nbsp;&nbsp;&nbsp;&nbsp;张三<h4>4.回到顶部，点击‘记录考勤’,开始考勤，如果存在分页，请点击下一页并且继续点击‘记录考勤’<h4>5.考勤结束，点击‘结束考勤’,系统会统计缺课名单,并且提示。</h4><h4>5.如果想统计多次考勤，请按照步骤4再次操作</h4><h4>6.如果想导出学生数据，请滑到底部，找到相对应班级，点击‘导出考勤表格’</h4></h4>', '使用提示', {
          dangerouslyUseHTMLString: true
        });
      }

		},
		created() {
			this.open()
		},
		mounted() {
			window.classlist = this.classlist;
		}
	})

</script>
<script>
	var index = 0;

	function selectFile(item) {
		document.getElementById('file').click();
		return index = item.getAttribute("index");
	}

	// 读取本地excel文件
	function readWorkbookFromLocalFile(file, callback) {
		var reader = new FileReader();
		reader.onload = function (e) {
			var data = e.target.result;
			var workbook = XLSX.read(data, { type: 'binary' });
			if (callback) callback(workbook);
		};
		reader.readAsBinaryString(file);
	}

	// 读取 excel文件
	function outputWorkbook(workbook) {
		var sheetNames = workbook.SheetNames; // 工作表名称集合
		sheetNames.forEach(name => {
			var worksheet = workbook.Sheets[name]; // 只能通过工作表名称来获取指定工作表
			for (var key in worksheet) {
				// v是读取单元格的原始值
				console.log(key, key[0] === '!' ? worksheet[key] : worksheet[key].v);
			}
		});
	}

	function readWorkbook(workbook) {
		var sheetNames = workbook.SheetNames; // 工作表名称集合
		var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
		var csv = XLSX.utils.sheet_to_csv(worksheet);
		var rows = csv.split('\n');
		rows.shift();
		rows.pop();
		rows.forEach((row, idx) => {
			var columns = row.split(',');
			window.classlist[index].student.push({
				name: columns[1],
				id: columns[0],
				state: []
			});
		});
	}

	$(function () {
		document.getElementById('file').addEventListener('change', function (e) {
			var files = e.target.files;
			if (files.length == 0) return;
			var f = files[0];
			if (!/\.xlsx$/g.test(f.name)) {
				alert('仅支持读取xlsx格式！');
				return;
			}
			readWorkbookFromLocalFile(f, function (workbook) {
				readWorkbook(workbook);
			});
		});
		//loadRemoteFile('./sample/test.xlsx');
	});

	var idTmr;

	function getExplorer() {
		var explorer = window.navigator.userAgent;
		//ie  
		if (explorer.indexOf("MSIE") >= 0) {
			return 'ie';
		}
		//firefox  
		else if (explorer.indexOf("Firefox") >= 0) {
			return 'Firefox';
		}
		//Chrome  
		else if (explorer.indexOf("Chrome") >= 0) {
			return 'Chrome';
		}
		//Opera  
		else if (explorer.indexOf("Opera") >= 0) {
			return 'Opera';
		}
		//Safari  
		else if (explorer.indexOf("Safari") >= 0) {
			return 'Safari';
		}
	}

	function method5(tableid, item) {
		if (getExplorer() == 'ie') {
			var curTbl = document.getElementsByClassName(tableid)[item.getAttribute("index")];
			var oXL = new ActiveXObject("Excel.Application");
			var oWB = oXL.Workbooks.Add();
			var xlsheet = oWB.Worksheets(1);
			var sel = document.body.createTextRange();
			sel.moveToElementText(curTbl);
			sel.select();
			sel.execCommand("Copy");
			xlsheet.Paste();
			oXL.Visible = true;

			try {
				var fname = oXL.Application.GetSaveAsFilename("Excel.xls",
					"Excel Spreadsheets (*.xls), *.xls");
			} catch (e) {
				print("Nested catch caught " + e);
			} finally {
				oWB.SaveAs(fname);
				oWB.Close(savechanges = false);
				oXL.Quit();
				oXL = null;
				idTmr = window.setInterval("Cleanup();", 1);
			}

		} else {
			tableToExcel(tableid, item.getAttribute("index"))
		}
	}

	function Cleanup() {
		window.clearInterval(idTmr);
		CollectGarbage();
	}
	var tableToExcel = (function () {
		var uri = 'data:application/vnd.ms-excel;base64,',
			template = '<html><head><meta charset="UTF-8"></head><body><table  border="1">{table}</table></body></html>',
			base64 = function (
				s) {
				return window.btoa(unescape(encodeURIComponent(s)))
			},
			format = function (s, c) {
				return s.replace(/{(\w+)}/g, function (m, p) {
					return c[p];
				})
			}
		return function (table, num, name) {
			if (!table.nodeType)
				table = document.getElementsByClassName(table)[num]
			var ctx = {
				worksheet: name || 'Worksheet',
				table: table.innerHTML
			}
			window.location.href = uri + base64(format(template, ctx))
		}
	})()
</script>